package com.alinesno.cloud.common.web.base.exceptions;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alinesno.cloud.common.web.base.form.FormRepeatException;
import com.alinesno.cloud.common.web.base.response.ResponseGenerator;

import cn.hutool.json.JSONUtil;

/**
 * web异常切面 默认spring aop不会拦截controller层，使用该类需要在spring公共配置文件中注入改bean，
 * 另外需要配置<aop:aspectj-autoproxy proxy-target-class="true"/>
 */
// @Aspect
// @Component
@Deprecated
public class WebExceptionAspect {
	
	private static final Logger log = LoggerFactory.getLogger(WebExceptionAspect.class);

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	private void webPointcut() {
	}

	/**
	 * 拦截web层异常，记录异常日志，并返回友好信息到前端 目前只拦截Exception，是否要拦截Error需再做考虑
	 *
	 * @param e
	 *            异常对象
	 */
	@AfterThrowing(pointcut = "webPointcut()", throwing = "e")
	public void handleThrowing(Exception e) {
		
		String message = e.getMessage();
		String errorMsg = null;
		String eclass = e.getClass().getName();
		
		log.debug("class name = {}" , eclass);
		
		if (e instanceof FormRepeatException) {
			errorMsg = e.getMessage();
		} else if (message != null && message.startsWith("com.linesno.training.common.exception.ServiceException")) {
			errorMsg = message.substring(message.indexOf(":") + 1, message.indexOf("\n") - 1);
		} else {
			errorMsg = StringUtils.isEmpty(e.getMessage()) ? "系统异常！" : e.getMessage();
		}
		
		log.error("服务业务异常", e);
		writeContent(errorMsg);
	}

	/**
	 * 将内容输出到浏览器
	 *
	 * @param content
	 *            输出内容
	 */
	private void writeContent(String content) {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/plain;charset=UTF-8");
		response.setHeader("icop-content-type", "exception");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			if (!(request.getHeader("accept").indexOf("application/json") > -1|| (request.getHeader("X-Requested-With") != null&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
				writer.print(content);
			} else {
				writer.print(JSONUtil.toJsonStr(ResponseGenerator.genFailMessage(content)));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.flush();
			writer.close();
		}
	}
}